<template>
  <el-container class="official-account-management_message-auto-reply">
    <el-main>
      <el-card shadow="never" class="tableCard">
        <el-tabs v-model="searchParams.eventType" @tab-click="handleClick">
          <el-tab-pane name="subscribe">
            <span slot="label"><i class="el-icon-star-off" />关注时回复</span>
            <vxe-toolbar :refresh="{ query: refreshChange }">
              <template v-slot:buttons>
                <el-button type="sccess" size="small" @click="syncFromWx(1)">从公众号同步</el-button>
              </template>
            </vxe-toolbar>
            <vxe-table
              ref="xTable"
              border
              resizable
              highlight-hover-row
              :auto-resize="true"
              :data="tableData"
              :loading="tableLoading"
              width
              max-height="500"
            >
              <vxe-table-column title="回复消息类型">
                <template slot-scope="scope">
                  <span
                    v-for="item in tableOption1.column[0].dicData"
                    v-show="item.value === scope.row.message.sourceType"
                    :key="item.index"
                  >{{ item.label }}</span>
                </template>
              </vxe-table-column>
              <vxe-table-column
                width="130"
                title="操作"
                fixed="right"
                align="center"
                slots="default"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    plain
                    @click="handleEdit(scope.row.id)"
                  >编辑</el-button>
                </template>
              </vxe-table-column>
            </vxe-table>
          </el-tab-pane>
          <el-tab-pane name="noKey">
            <span slot="label"><i class="el-icon-chat-line-round" />收到消息回复</span>
            <vxe-toolbar :refresh="{ query: refreshChange }">
              <template v-slot:buttons>
                <el-button type="sccess" size="small" @click="syncFromWx(2)">从公众号同步</el-button>
              </template>
            </vxe-toolbar>
            <vxe-table
              ref="xTable"
              border
              resizable
              highlight-hover-row
              :auto-resize="true"
              :data="tableData"
              :loading="tableLoading"
              width
              max-height="500"
            >
              <vxe-table-column title="回复消息类型">
                <template slot-scope="scope">
                  <span
                    v-for="item in tableOption1.column[0].dicData"
                    v-show="item.value === scope.row.message.sourceType"
                    :key="item.index"
                  >{{ item.label }}</span>
                </template>
              </vxe-table-column>
              <vxe-table-column
                width="130"
                title="操作"
                fixed="right"
                align="center"
                slots="default"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    plain
                    @click="handleEdit(scope.row.id)"
                  >编辑</el-button>
                  <!-- <el-button type="text" icon="el-icon-delete" size="small" plain @click="handleDel(scope.row.id)">删除</el-button> -->
                </template>
              </vxe-table-column>
            </vxe-table>
          </el-tab-pane>
          <el-tab-pane name="key">
            <span slot="label"><i class="el-icon-news" />关键词回复</span>
            <vxe-toolbar :refresh="{ query: refreshChange }">
              <template v-slot:buttons>
                <el-button type="sccess" size="small" @click="syncFromWx(3)">从公众号同步</el-button>
                <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
              </template>
            </vxe-toolbar>
            <vxe-table
              ref="xTable"
              border
              resizable
              highlight-hover-row
              :auto-resize="true"
              :data="tableData"
              :loading="tableLoading"
              width
              height="500"
              :print-config="{}"
            >
              <vxe-table-column width="50" type="seq" title=" " />
              <vxe-table-column
                field="ruleName"
                title="关键词名称"
              />
              <vxe-table-column field="repMate" title="匹配类型">
                <template slot-scope="scope">
                  {{ scope.row.repMate === "1" ? "全匹配" : "半匹配" }}
                </template>
              </vxe-table-column>
              <vxe-table-column title="回复消息类型">
                <template slot-scope="scope">
                  <span
                    v-for="item in tableOption1.column[0].dicData"
                    v-show="item.value === scope.row.message.sourceType"
                    :key="item.index"
                  >{{ item.label }}</span>
                </template>
              </vxe-table-column>
              <vxe-table-column
                width="130"
                title="操作"
                fixed="right"
                align="center"
                slots="default"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleEdit(scope.row.id)"
                  >编辑</el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDel(scope.row.id)"
                  >删除</el-button>
                </template>
              </vxe-table-column>
            </vxe-table>
            <vxe-pager
              :current-page.sync="searchParams.pageNum"
              :page-size.sync="searchParams.pageSize"
              :total="total"
              :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'FullJump',
                'Total',
              ]"
              @page-change="getPage"
            />
          </el-tab-pane>
        </el-tabs>
        <el-dialog v-if="dialog1Visible" :title="title == 'add' ? '新增回复消息' : '修改回复消息'" :close-on-click-modal="false" :visible.sync="dialog1Visible">
          <el-form ref="replyForm" :model="objData" :rules="replyRules" label-position="right" label-width="7rem">
            <el-row :gutter="40">
              <!-- <el-col v-if="searchParams.eventType == 'noKey'" :span="13">
                <el-form-item label="请求消息类型" prop="reqType">
                  <el-select v-model="objData.reqType" placeholder="请选择">
                    <el-option
                      v-for="item in dictData.get('wx_req_type')"
                      v-show="item.value !== 'event'"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col v-if="searchParams.eventType == 'key'" :span="13">
                <el-form-item label="关键词名称：" prop="ruleName">
                  <el-input v-model="objData.ruleName" placeholder="请输入内容" clearable />
                </el-form-item>
              </el-col>
              <!-- <el-col v-if="searchParams.eventType == 'key'" :span="13">
                <el-form-item label="匹配类型" prop="repMate">
                  <el-select v-model="objData.repMate" placeholder="请选择" style="width: 100px">
                    <el-option
                      v-for="item in dictData.get('wx_rep_mate')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col v-if="searchParams.eventType == 'key'" :span="24">
                <el-form-item label="关键词：" prop="keysName">
                  <el-input v-model="objData.keysName" placeholder="请输入内容：" type="textarea" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="回复消息：">
                  <WxReplySelect ref="WxReplySelect" :obj-data="tempObj" @updateMenu="updateMenu" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialog1Visible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
import { checkVaildWxMp, addAutoReplyMessage, modifyAutoReplyMessage, delAutoReplyMessage, viewAutoReplyMessage, listAutoReplyMessage, syncAutoReplayMessageFromWx } from '@/api/wxMp'
import { tableOption1 } from '@/const/crud/wxmp/wxautoreply'
import WxReplySelect from '@/components/wechat-mp/reply'
export default {
  components: { WxReplySelect },
  data() {
    return {
      searchParams: {
        appId: '',
        eventType: 'subscribe',
        ruleName: '',
        pageNum: 1,
        pageSize: 20
      },
      total: 1,
      tempObj: {
        sourceType: 'TEXT',
        unionKey: '',
        mpSourceNewsPageVos: [],
        appId: '',
        repUrl: '',
        repName: ''
      },
      replyRules: {
        ruleName: [
          { required: true, message: '请填写关键词名称', trigger: 'blur' }
        ],
        keysName: [
          { required: true, message: '请输入关键词', trigger: 'blur' }
        ]
      },
      afterParams: {
        appId: ''
      },

      tableData: [],
      tableLoading: false,
      tableOption1: tableOption1,
      dialog1Visible: false,
      objData: {
        appId: '',
        eventType: 'subscribe',
        ruleName: '',
        keysName: '',
        keys: [],
        message: {}
      },
      title: null
    }
  },
  created() {
    this.init()
  },
  methods: {
    updateMenu(val) {
      this.objData.message = val
    },
    refreshParams(params) {
      this.searchParams = params
      this.getList1()
    },
    init() {
      checkVaildWxMp().then(res => {
        if (res) {
          if (res === undefined) {
            alert('公众号没有授权，请授权后再操作1!')
            this.$router.push(`/wxMp/wxMpAuthorize`)
          } else {
            const objRes = JSON.parse(JSON.stringify(res))
            this.searchParams.appId = objRes.appId
            this.tempObj.appId = objRes.appId
            this.objData.appId = objRes.appId
            this.afterParams.appId = objRes.appId
            this.getPage()
          }
        } else {
          alert('公众号没有授权，请授权后再操作2!')
          this.$router.push(`/wxMp/wxMpAuthorize`)
        }
      })
    },
    getList1() {
      this.getPage()
    },
    syncFromWx(type) {
      this.tableLoading = true
      syncAutoReplayMessageFromWx({ type }).then(res => {
        if (res) {
          this.getList1()
          this.tableLoading = false
        } else {
          this.tableLoading = false
        }
      })
    },
    handleAdd() {
      this.title = 'add'
      this.dialog1Visible = true
      this.objData = {
        eventType: 'key',
        ruleName: '',
        keysName: '',
        keys: [],
        message: {}
      }
      this.tempObj = {
        sourceType: 'TEXT',
        unionKey: '',
        mpSourceNewsPageVos: [],
        repUrl: '',
        repName: ''
      }
      this.tempObj.appId = this.searchParams.appId
      this.objData.appId = this.searchParams.appId
    },
    handleEdit(id) {
      this.title = 'edit'
      viewAutoReplyMessage({ id }).then((res) => {
        res.keysName = res.keys ? res.keys.join(',') : ''
        this.objData = res
        this.tempObj = res.message
        this.tempObj.appId = this.searchParams.appId
        this.dialog1Visible = true
      })
    },
    handleClick(tab, event) {
      this.tableData = []
      this.searchParams.pageNum = 1
      this.getPage()
    },
    getPage() {
      this.tableLoading = true
      listAutoReplyMessage(this.searchParams).then((res) => {
        this.tableData = res.records
        this.total = res.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delAutoReplyMessage({ id }).then(() => {
            this.$message.success('删除成功！')
            this.getPage()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    handleSubmit(row) {
      this.$refs.replyForm.validate((valid) => {
        if (valid) {
          const type = this.$refs.WxReplySelect.parentParams.sourceType
          const content =
            this.objData.message.unionKey === undefined
              ? ''
              : this.objData.message.unionKey
          if (type === 'TEXT' && content.trim() === '') {
            this.$message.error('请输入文本')
            return false
          }
          if (type === 'PIC' && content === '') {
            this.$message.error('请选择图片')
            return false
          }
          if (type === 'VOICE' && content === '') {
            this.$message.error('请选择音频')
            return false
          }
          if (type === 'VIDEO' && content === '') {
            this.$message.error('请选择视频')
            return false
          }
          if (type === 'IMAGE_TEXT' && content === '') {
            this.$message.error('请选择图文')
            return false
          }
          if (this.searchParams.eventType === 'key') {
            this.objData.keys = this.objData.keysName.split(',')
          }
          if (this.title === 'add') {
            addAutoReplyMessage(this.objData).then((data) => {
              this.$message.success('新增成功！')
              this.dialog1Visible = false
              this.getPage()
            })
          }
          if (this.title === 'edit') {
            modifyAutoReplyMessage(this.objData).then((data) => {
              this.$message.success('修改成功！')
              this.dialog1Visible = false
              this.getPage()
            })
          }
        }
      })
    },
    /**
     * 刷新回调
     */
    refreshChange(page) {
      this.getPage()
    }
  }
}
</script>

<style>
</style>
